package com.settlement.system.common.util.common;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;

import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

/**
 * 手动策略本地缓存工具类
 * @author hc
 */
public class CacheUtil {

    public static Cache<String, Object> cacheManager = Caffeine.newBuilder()
            .expireAfterWrite(3, TimeUnit.HOURS)
            .maximumSize(1000)
            .build();

    /**
     * 存储
     * @param key 缓存key
     * @param value 缓存值
     */
    public static void setValue(String key, Object value){
        if (StringUtils.isNotBlank(key)) {
            cacheManager.put(key,value);
        }
    }

    /**
     * 指定获取
     * @param key 缓存key
     * @return 缓存数据
     */
    public static Object getValue(String key){
        if (StringUtils.isNotBlank(key)) {
            return cacheManager.getIfPresent(key);
        }
        return null;
    }

    /**
     * 所有缓存
     * @return 获取所有的缓存
     */
    public static ConcurrentMap<String, Object> getAllCache(){
        ConcurrentMap<@NonNull String, @NonNull Object> concurrentMap = cacheManager.asMap();
        return concurrentMap;
    }

    /**
     * 指定删除
     * @param key 删除指定key
     */
    public static void delValue(String key){
        if (StringUtils.isNotBlank(key)) {
            cacheManager.invalidate(key);
        }
    }

    /**
     * 批量删除
     * @param keys 指定keys
     */
    public static void delBatchValue(List<String> keys){
        if (CollectionUtils.isNotEmpty(keys)) {
            cacheManager.invalidateAll(keys);
        }
    }
    /**
     * 删除全部
     */
    public static void delAllValue(){
       cacheManager.invalidateAll();
    }

}